<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>函数防抖</title>
	<style>
		#container{
		    width: 100%; height: 200px; line-height: 200px; text-align: center; color: #fff; background-color: #444; font-size: 30px;
		}
	</style>
</head>
<body>
	<a href="https://github.com/mqyqingfeng/Blog/issues/22">链接</a>
	<div id="container"></div>
	<div id="button">按钮</div>
	<script>
		// var count = 1;
		// var container = document.getElementById('container');
		// function getUserAction(event){
		// 	console.log(event)
		// 	console.log(this)
		// 	container.innerHTML = count ++ ;
		// }

		// function debounce(fn,wait){
		// 	var timeout;
		// 	return function(){
		// 		var self = this;
		// 		var args = arguments;
		// 		clearTimeout(timeout);
		// 		timeout = setTimeout(function(){
		// 			fn.call(self ,args)
		// 			// 相同:fn.apply(self)
		// 		},wait)
		// 	}
		// }

		// function debounce(fn,wait,immediate){
		// 	var timeout;
		// 	var result ;
		// 	return function(){
		// 		var context = this;
		// 		var args = arguments;
		// 		if(timeout) clearTimeout(timeout);
		// 		if(immediate){
		// 			var callNow = !timeout;
		// 			timeout = setTimeout(function(){
		// 				timeout = null;
		// 			},wait)
		// 			if(callNow) result = fn.apply(context,args);
		// 		}else{
		//             timeout = setTimeout(function(){
		//                 func.apply(context, args)
		//             }, wait);
		// 		}
		// 		return result
		// 	}
		// }

		function debounce(fn,wait,immediate){
			var timeout;
			var result;

			var debounced = function() { 
				var context = this;
				var args = arguments;
				if(timeout) clearTimeout(timeout);
				if(immediate){
					var callNow = !timeout;
					timeout = setTimeout(function(){
						timeout = null;
					},wait)

					if(callNow) result = fn.apply(context,args)
				}else{
					timeout = setTimeout(function(){
						fn.apply(context,args)
					},wait)
				}
			}
			debounced.cancel = function(){
				clearTimeout(timeout);
				timeout = null;
			}
			return debounced;
		}
		var count = 1;
		var container = document.getElementById('container');

		function getUserAction(e) {
		    container.innerHTML = count++;
		};

		var setUseAction = debounce(getUserAction, 1000, true);

		container.onmousemove = setUseAction;

		document.getElementById("button").addEventListener('click', function(){
		    setUseAction.cancel();
		})
	</script>
</body>
</html>